from django.shortcuts import render

# Create your views here.

# /news/top/  顶部新闻：轮播新闻 推荐新闻  图片新闻
# 轮播图新闻： is_slide为True
# 推荐新闻：按新闻发布时间的降序排序，查询最新添加的10条新闻，作为界面的推荐新闻显示出来
# 图片新闻：img_url不为空，并且点击量click最多click最多4条新闻查询处理，显示在界面上
from rest_framework.response import Response
from rest_framework.views import APIView

from news.models import News, NewsCategory
from news.serializers import SlideNewsSerializer, TopNewsSerializer, ImgNewsAlbumSerializer, \
    OneCategoryNewsAlbumSerializer, TwoCategoryNewsAlbumSerializer


class TopAPIView(APIView):
    def get(self, request):

        # slide_news = News.objects.filter('is_slide'==1)
        slide_news = News.objects.filter(is_slide__exact=1)

        top_news = News.objects.all().order_by('-create_time')[0:10]

        image_news = News.objects.exclude (img_url='').order_by('-click')[0:4]
        slide_serializer = SlideNewsSerializer(slide_news,many=True)
        top_serializer = TopNewsSerializer(top_news, many=True)
        image_serializer = ImgNewsAlbumSerializer(image_news, many=True)
        data = {
            'slide_news': slide_serializer.data,
            'top_news': top_serializer.data,
            'image_news': image_serializer.data
        }
        return Response(data)


        # 获取查询集:
        # books = BookInfo.objects.all()
        # 调用序列化器, 对查询集进行序列化处理
        # serializer = BookInfoSerializer(books, many=True)
        # 处理完成的数据, 再经过 Response 类的处理就会变成 json
        # return Response(serializer.data)


# /news/category/ 获取类别新闻
# 类别分为一级分类和二级分类，都存储在一张表中，使用到了自关联(有一个字段保存上级类别的id)
class CategoryAPIView(APIView):
    def get(self, request):

        # 获取所有的一级分类NewsCategory.objects.filter(parent_id=0)
        one_news = NewsCategory.objects.filter(parent_id__exact=0)
        # 存储所有的大类数据
        newsData_list_data = []

        for oneNew in one_news:
            # 序列化大类的数据
            one_new = OneCategoryNewsAlbumSerializer(oneNew).data
            # 获取当前类下的所有二级分类
            two_news = oneNew.newscategory_set.all()
            # 用于存储二级分类的列表
            newscategory_set = []
            twoNew_id_list = []

            for twoNew in two_news:
                two_New = OneCategoryNewsAlbumSerializer(twoNew).data
                twoNew_id_list.append(two_New['id'])
                newscategory_set.append(two_New)

            one_new['newscategory_set'] = newscategory_set

            # 存储当前类别下时间最新的4条
            news_to4= News.objects.filter(category_id__in=twoNew_id_list).order_by('-create_time').exclude(img_url='')[0:4]
            news = TwoCategoryNewsAlbumSerializer(news_to4,many=True).data
            one_new['news'] = news

            # 存储当前类别下点击量最高的8条
            news_to8 = News.objects.filter(category_id__in=twoNew_id_list).order_by('-click')[0:8]
            to8 = TwoCategoryNewsAlbumSerializer(news_to8, many=True).data
            one_new['top8'] = to8
            newsData_list_data.append(one_new)

        return Response(newsData_list_data)
































